import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gluz/app/common/extension/string_extension.dart';
import 'package:gluz/app/data/api_response.dart';
import 'package:gluz/app/modules/login/controllers/login_controller.dart';
import 'package:gluz/app/utils/h5_url_manager.dart';
import 'package:gluz/app/utils/toast_util.dart';

import '../../../../../app_session.dart';
import '../../../../common/bottom_modal_sheet.dart';
import '../../../../common/native_bridge.dart';
import '../../../../data/country_entity.dart';
import '../../../../routes/app_pages.dart';
import '../../../../utils/http_util.dart';
import 'package:dio/dio.dart' as dio;

class RegisterController extends GetxController {
  //TODO: Implement RegisterController
  final loginController = Get.find<LoginController>();
  TextEditingController phoneController = TextEditingController();
  TextEditingController pwdController = TextEditingController();
  TextEditingController verifyController = TextEditingController();
  TextEditingController inviteController = TextEditingController();
  var isCheckLink = true;
  String verifyText = "获取验证码".tr;
  int _countdown = 60;
  Timer? _timer;
  String faceImageBase64String = '';

  // 中文语言选择事件
  void onChineseLanguageSelected() {
    // 实现中文语言选择逻辑
    app.translationToCN();
    update();
  }

  // 俄文语言选择事件
  void onRussianLanguageSelected() {
    // 实现俄文语言选择逻辑
    app.translationToRU();
    update();
  }

  /// 选择国家
  void onTapCountry() {
    BottomModalSheet.showCountryList((entity) {
      loginController.selectedCountry = entity;
      loginController.update();
      update();
    });
  }
  
  void onTapVerify() async {
    if (phoneController.text.isPhoneNumerValid(loginController.selectedCountry.id) == false) {
      ToastUtil.show('请输入正确的手机号'.tr);
      return;
    }
    if (verifyText == '获取验证码'.tr) {
      ToastUtil.showLoading();
      ApiResponse? response = await app.http.request(path: '/api/sms/code', params: {
        'countryCode': loginController.selectedCountry.code,
        'phonenumber': phoneController.text,
      }, fromJson: (data) => ApiResponse.fromJson(data));
      if (response?.success == true) {
        startCountdown();
        ToastUtil.dismiss();
      } else {
        verifyText == '获取验证码'.tr;
        ToastUtil.dismiss();
      }
    }
  }

  void startCountdown() {
    _countdown = 60;
    verifyText = '$_countdown';
    update();
    _timer?.cancel();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _countdown--;
      if (_countdown > 0) {
        verifyText = '$_countdown';
        update();
      } else {
        verifyText = '获取验证码'.tr;
        update();
        _timer?.cancel();
      }
    });
  }


  // 用户协议点击事件
  void onUserAgreementTapped() {
    // 实现用户协议查看逻辑
    Get.toNamed(
      Routes.WEBVIEW,
      arguments: {
        'url': H5UrlManager.userPrivacyUrl('隐私政策'),
      },
    );
  }

  void onRegisterButtonPressed() {
    if (phoneController.text.isPhoneNumerValid(loginController.selectedCountry.id) == false) {
      ToastUtil.show('请输入正确的手机号'.tr);
      return;
    }
    if (pwdController.text.trim().length < 8) {
      ToastUtil.show('请输入 8 位以上的密码'.tr);
      return;
    }
    if (verifyController.text.isEmpty && loginController.selectedCountry.id == 0) {
      ToastUtil.show('请输入短信验证码'.tr);
      return;
    }
    if (isCheckLink == false) {
      Get.dialog(
        CupertinoAlertDialog(
          title: Text('提示'.tr),
          content: Text('阅读并同意《GLUZ用户服务协议和隐私政策》'.tr),
          actions: [
            CupertinoDialogAction(child: Text('拒绝'.tr), onPressed: () {
              Get.back();
              },),
            CupertinoDialogAction(child: Text('同意'.tr), onPressed: () {
              isCheckLink = true;
              update();
              jumpRegisterInfoPage();
              },),
          ],
        )
      );
      return;
    }
    jumpRegisterInfoPage();
  }

  void jumpRegisterInfoPage() async {
    if (loginController.selectedCountry.id == 0) {
      Get.toNamed(Routes.REGISTER_INFO);
      return;
    }
    // 唤起人脸识别
    ToastUtil.showLoading();
    if (GetPlatform.isAndroid) {
      await NativeBridge.invokeMethodToNative('requestMediaProjection', {});
    }
    ApiResponse? apiResponse = await app.http.request(
      method: Method.post,
      path: '/api/finauth/bizToken',
      fromJson: (e) => ApiResponse.fromJson(e),);
    String? token = apiResponse?.data['biz_token'];
    bool result = await NativeBridge.invokeMethodToNative('faceAuth', {"token": token});
    if (result) {
      Map<String, dynamic> params = {
        "bizToken": token,
        "dataType": '0',
      };
      ApiResponse? apiResponse = await app.http.request(
        method: Method.post,
        path: '/api/finauth/liveness',
        params: dio.FormData.fromMap(params),
        fromJson: (e) => ApiResponse.fromJson(e),);
      faceImageBase64String = apiResponse?.data['images']['image_best'];
      if (faceImageBase64String.isNotEmpty) {
        ToastUtil.dismiss();
        Get.toNamed(Routes.REGISTER_INFO);
      } else {
        ToastUtil.show('人脸验证失败'.tr);
      }
    } else {
      ToastUtil.show('人脸识别失败'.tr);
    }
  }

  void onServerTap() {

  }


  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
  }

}
